import { useUnload } from "@tarojs/taro"
import { useRef, useState } from "react"

export function useCutdown(duration: number) {
  const timer = useRef<NodeJS.Timeout>()
  const [remain, setRemain] = useState(duration)
  const [running, setRunning] = useState(false)
  function start() {
    setRunning(true)
    clearTimer()
    timer.current = setTimeout(() => {
      setRemain(remain - 1)
      if (remain < 0) {
        stop()
      } else {
        start()
      }
    }, 1000);
  }
  function stop() {
    setRunning(false)
    clearTimer()
    setRemain(duration)
  }
  function pause() {
    setRunning(false)
    clearTimer()
  }
  function clearTimer() {
    if (timer.current) {
      clearTimeout(timer.current)
    }
  }
  useUnload(clearTimer)
  return {
    remain,
    running,
    start,
    stop,
    pause
  }
}
